<script setup lang="ts">
import { ref } from 'vue';

import {
  ClockCircleOutlined,
  FileTextOutlined,
  PlusOutlined,
  SafetyCertificateOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

const createWillModal = ref(false);
const showAuthModal = ref(false);
const contractSigningModal = ref(false);
const contractDeployModal = ref(false);
const selectedContract = ref<any>(null);

// 遗嘱列表
const wills = ref([
  {
    id: 1,
    title: '朱元璋遗嘱',
    createdAt: '1398-06-24',
    witnesses: ['朱标', '朱棣', '徐达'],
    notarized: true,
    hash: '0x1234...5678',
  },
  {
    id: 2,
    title: '朱棣遗嘱',
    createdAt: '1424-08-12',
    witnesses: ['朱高炽', '朱瞻基'],
    notarized: false,
    hash: '0xabcd...efgh',
  },
]);

// 教育基金
const educationFund = ref({
  total: 500,
  distributed: 320,
  beneficiaries: 12,
});

const educationRecords = ref([
  {
    student: '朱见深',
    amount: 50_000,
    semester: '2025春季',
    gpa: 3.8,
    status: 'approved',
  },
  {
    student: '朱祁镇',
    amount: 50_000,
    semester: '2025春季',
    gpa: 3.6,
    status: 'approved',
  },
  {
    student: '朱祁钰',
    amount: 50_000,
    semester: '2025春季',
    gpa: 3.9,
    status: 'pending',
  },
]);

const educationColumns = [
  { title: '学生', dataIndex: 'student', key: 'student' },
  { title: '金额', key: 'amount' },
  { title: '学期', dataIndex: 'semester', key: 'semester' },
  { title: 'GPA', dataIndex: 'gpa', key: 'gpa' },
  { title: '状态', key: 'status' },
];

// 公益基金
const charityFund = ref({
  total: 300,
  donated: 180,
  projects: 8,
});

const charityProjects = ref([
  { name: '贫困学生助学金', amount: 500_000, beneficiaries: 50 },
  { name: '家族祠堂修缮', amount: 800_000, beneficiaries: 1 },
  { name: '文化遗产保护', amount: 300_000, beneficiaries: 3 },
]);

// 法律存证
const legalProofs = ref([
  {
    id: 1,
    title: '家族章程',
    timestamp: '2025-01-01 10:00:00',
    hash: '0x7a8f...b4e9',
    notary: '北京市第一公证处',
  },
  {
    id: 2,
    title: '资产分配协议',
    timestamp: '2025-02-15 14:30:00',
    hash: '0x3c5d...9f2a',
    notary: '上海市公证处',
  },
]);

const newWill = ref({
  title: '',
  content: '',
  witnesses: [],
  requireNotary: true,
});

// 普通合同模板（非智能合约）
const documentTemplates = ref([
  {
    id: 1,
    name: '遗产分配协议',
    category: '继承',
    description: '标准遗产分配合同模板',
    useCount: 15,
  },
  {
    id: 2,
    name: '教育基金协议',
    category: '基金',
    description: '教育基金设立和管理协议',
    useCount: 8,
  },
  {
    id: 3,
    name: '家族章程',
    category: '治理',
    description: '家族治理规则和章程',
    useCount: 23,
  },
  {
    id: 4,
    name: '资产托管协议',
    category: '资产',
    description: '资产托管和管理协议',
    useCount: 12,
  },
  {
    id: 5,
    name: '公益捐赠协议',
    category: '公益',
    description: '公益项目捐赠合同',
    useCount: 6,
  },
  {
    id: 6,
    name: '保密协议',
    category: '隐私',
    description: '家族信息保密协议',
    useCount: 20,
  },
]);

// 律所信息
const lawFirms = ref([
  {
    id: 1,
    name: '金杜律师事务所',
    expertise: ['遗产继承', '家族信托', '税务筹划'],
    serviceCount: 12,
    rating: 4.5,
  },
  {
    id: 2,
    name: '君合律师事务所',
    expertise: ['资产管理', '公司法务', '争议解决'],
    serviceCount: 8,
    rating: 4.8,
  },
]);

// 咨询记录
const consultations = ref([
  {
    id: 1,
    topic: '遗产税务优化咨询',
    lawyer: '金杜律师事务所-王律师',
    time: '2025-09-15 14:00',
  },
  {
    id: 2,
    topic: '家族信托设立咨询',
    lawyer: '君合律师事务所-李律师',
    time: '2025-08-20 10:30',
  },
]);

// 仲裁案件
const arbitrationCases = ref([
  {
    id: 1,
    caseNo: 'ARB-2025-001',
    parties: '朱棣 vs 朱允炆',
    subject: '藩国财产分配争议',
    filingDate: '2025-03-01',
    status: 'resolved',
  },
  {
    id: 2,
    caseNo: 'ARB-2025-002',
    parties: '朱高炽 vs 朱高煦',
    subject: '教育基金使用权',
    filingDate: '2025-05-15',
    status: 'pending',
  },
]);

const arbitrationColumns = [
  { title: '案号', dataIndex: 'caseNo', key: 'caseNo' },
  { title: '当事人', dataIndex: 'parties', key: 'parties' },
  { title: '争议标的', dataIndex: 'subject', key: 'subject' },
  { title: '立案日期', dataIndex: 'filingDate', key: 'filingDate' },
  { title: '状态', key: 'status' },
  { title: '操作', key: 'action' },
];

const newAuth = ref({
  institution: '',
  dataTypes: [],
  duration: '6',
});

// 智能合约模板
const contractTemplates = ref([
  {
    id: 'template-1',
    name: '资产继承合约',
    description: '自动执行资产分配，支持多继承人，可设置触发条件',
    category: 'inheritance',
    gasEstimate: 0.015,
    parameters: [
      {
        name: 'beneficiaries',
        label: '受益人地址',
        type: 'array',
        required: true,
      },
      { name: 'shares', label: '分配比例(%)', type: 'array', required: true },
      {
        name: 'unlockTime',
        label: '解锁时间',
        type: 'datetime',
        required: false,
      },
      { name: 'conditions', label: '触发条件', type: 'text', required: false },
    ],
  },
  {
    id: 'template-2',
    name: '教育基金合约',
    description: '按学期自动发放教育基金，支持GPA要求和自动审核',
    category: 'education',
    gasEstimate: 0.012,
    parameters: [
      { name: 'student', label: '学生地址', type: 'address', required: true },
      {
        name: 'amountPerSemester',
        label: '每学期金额',
        type: 'number',
        required: true,
      },
      { name: 'minGPA', label: '最低GPA要求', type: 'number', required: true },
      { name: 'duration', label: '资助年限', type: 'number', required: true },
    ],
  },
  {
    id: 'template-3',
    name: '公益捐赠合约',
    description: '定期向慈善机构捐赠，支持多机构分配和透明度跟踪',
    category: 'charity',
    gasEstimate: 0.01,
    parameters: [
      {
        name: 'charities',
        label: '慈善机构地址',
        type: 'array',
        required: true,
      },
      { name: 'amounts', label: '捐赠金额', type: 'array', required: true },
      {
        name: 'frequency',
        label: '捐赠频率',
        type: 'select',
        required: true,
        options: ['monthly', 'quarterly', 'yearly'],
      },
    ],
  },
  {
    id: 'template-4',
    name: '家族契约',
    description: '多方签署的家族章程，支持投票修改和链上存证',
    category: 'governance',
    gasEstimate: 0.02,
    parameters: [
      { name: 'signers', label: '签署人地址', type: 'array', required: true },
      {
        name: 'content',
        label: '契约内容IPFS哈希',
        type: 'text',
        required: true,
      },
      {
        name: 'votingThreshold',
        label: '修改投票阈值(%)',
        type: 'number',
        required: true,
      },
    ],
  },
]);

// 已部署的智能合约
const deployedContracts = ref([
  {
    id: 'contract-1',
    name: '朱元璋遗产分配合约',
    template: '资产继承合约',
    address: '0x1234567890abcdef1234567890abcdef12345678',
    deployer: '朱元璋',
    deployedAt: '2025-01-15 10:00:00',
    status: 'active',
    beneficiaries: 3,
    totalValue: 10_000_000,
    txHash: '0xabc123def456789...',
    signers: [
      {
        name: '朱元璋',
        address: '0x1111...',
        signed: true,
        time: '2025-01-15 10:00:00',
      },
      {
        name: '朱棣',
        address: '0x2222...',
        signed: true,
        time: '2025-01-15 10:30:00',
      },
      {
        name: '朱高炽',
        address: '0x3333...',
        signed: true,
        time: '2025-01-15 11:00:00',
      },
    ],
  },
  {
    id: 'contract-2',
    name: '家族教育基金',
    template: '教育基金合约',
    address: '0xabcdef1234567890abcdef1234567890abcdef12',
    deployer: '朱棣',
    deployedAt: '2025-02-01 14:00:00',
    status: 'active',
    beneficiaries: 5,
    totalValue: 5_000_000,
    txHash: '0xdef456abc789123...',
    signers: [
      {
        name: '朱棣',
        address: '0x2222...',
        signed: true,
        time: '2025-02-01 14:00:00',
      },
      {
        name: '朱高炽',
        address: '0x3333...',
        signed: true,
        time: '2025-02-01 14:20:00',
      },
    ],
  },
]);

// 新建合约表单
const newContract = ref({
  templateId: '',
  name: '',
  parameters: {} as Record<string, any>,
});

function viewWill(item: any) {
  message.info(
    `查看遗嘱：${item.title}\n哈希：${item.hash}\n公证状态：${item.notarized ? '已公证' : '待公证'}`,
  );
}

function notarizeWill(item: any) {
  if (item.notarized) {
    message.warning('此遗嘱已经公证');
    return;
  }
  message.loading('正在联系公证处...', 2);
  setTimeout(() => {
    message.success('公证申请已提交！\n公证处将在3个工作日内完成审核');
  }, 2000);
}

function saveWill() {
  message.loading('遗嘱上链存证中...', 2);
  setTimeout(() => {
    message.success(
      '遗嘱已上链保存！\n✓ 内容哈希已存证\n✓ 见证人已签名\n✓ 智能合约已部署\n交易哈希: 0x9876...4321',
    );
    createWillModal.value = false;
  }, 2000);
}

function downloadCertificate(item: any) {
  message.success('正在生成公证书PDF...');
}

function useTemplate(template: any) {
  message.info(
    `使用模板：${template.name}\n✓ 自动填充家族信息\n✓ 智能合约集成\n✓ 一键上链存证`,
  );
}

function consultLawyer(firm: any) {
  message.info(
    `预约咨询：${firm.name}\n专长：${firm.expertise.join('、')}\n评分：${firm.rating}星\n在线预约或电话联系`,
  );
}

function viewCases(firm: any) {
  message.info(
    `查看${firm.name}服务案例：\n✓ 成功案例：${firm.serviceCount}件\n✓ 平均周期：30天\n✓ 客户满意度：${firm.rating * 20}%`,
  );
}

function viewCase(record: any) {
  message.info(
    `案件详情：\n案号：${record.caseNo}\n当事人：${record.parties}\n争议：${record.subject}\n状态：${record.status === 'resolved' ? '已结案' : '审理中'}`,
  );
}

function downloadVerdict(record: any) {
  message.success(`正在生成裁决书PDF：${record.caseNo}`);
}

function addAuthorization() {
  message.success('数据授权已生成！机构可在授权期限内访问指定数据');
  showAuthModal.value = false;
}

// 智能合约相关函数
function selectTemplate(template: any) {
  newContract.value.templateId = template.id;
  newContract.value.name = '';
  newContract.value.parameters = {};
  contractDeployModal.value = true;
}

function deployContract() {
  const template = contractTemplates.value.find(
    (t) => t.id === newContract.value.templateId,
  );
  if (!template) {
    message.error('请选择合约模板');
    return;
  }

  if (!newContract.value.name) {
    message.error('请输入合约名称');
    return;
  }

  message.loading('正在部署智能合约...', 3).then(() => {
    const newDeployedContract = {
      id: `contract-${Date.now()}`,
      name: newContract.value.name,
      template: template.name,
      address: `0x${Math.random().toString(16).slice(2)}${Math.random().toString(16).slice(2)}`,
      deployer: '朱瞻基（当前用户）',
      deployedAt: new Date().toLocaleString('zh-CN'),
      status: 'pending',
      beneficiaries: 0,
      totalValue: 0,
      txHash: `0x${Math.random().toString(16).slice(2)}${Math.random().toString(16).slice(2)}`,
      signers: [
        {
          name: '朱瞻基',
          address: '0x4444...',
          signed: true,
          time: new Date().toLocaleString('zh-CN'),
        },
      ],
    };

    deployedContracts.value.unshift(newDeployedContract);
    message.success(
      `智能合约部署成功！\n✓ 合约地址: ${newDeployedContract.address}\n✓ 交易哈希: ${newDeployedContract.txHash}\n✓ Gas消耗: ${template.gasEstimate} ETH`,
    );
    contractDeployModal.value = false;
  });
}

function viewContract(contract: any) {
  selectedContract.value = contract;
  message.info(
    `合约详情：\n名称：${contract.name}\n地址：${contract.address}\n部署者：${contract.deployer}\n状态：${contract.status === 'active' ? '运行中' : '待激活'}`,
  );
}

function signContract(contract: any) {
  selectedContract.value = contract;
  contractSigningModal.value = true;
}

function confirmSignContract() {
  if (!selectedContract.value) return;

  message.loading('正在签署合约...', 2).then(() => {
    // 添加当前用户的签名
    const newSigner = {
      name: '朱瞻基（当前用户）',
      address: '0x4444...',
      signed: true,
      time: new Date().toLocaleString('zh-CN'),
    };

    const contract = deployedContracts.value.find(
      (c) => c.id === selectedContract.value.id,
    );
    if (contract) {
      contract.signers.push(newSigner);
      if (contract.signers.length >= 3) {
        contract.status = 'active';
      }
    }

    message.success(
      `链上签署成功！\n✓ 签名已上链\n✓ 交易哈希: 0x${Math.random().toString(16).slice(2)}\n✓ Gas消耗: 0.003 ETH`,
    );
    contractSigningModal.value = false;
  });
}

function executeContract(contract: any) {
  message.loading('正在执行合约...', 2).then(() => {
    message.success(
      `合约执行成功！\n✓ 合约: ${contract.name}\n✓ 执行结果已上链\n✓ 交易哈希: 0x${Math.random().toString(16).slice(2)}`,
    );
  });
}
</script>

<template>
  <div class="legal-compliance">
    <a-card title="⚖️ 法律合规中心">
      <a-tabs>
        <!-- 遗嘱管理 -->
        <a-tab-pane key="will" tab="📜 遗嘱管理">
          <a-button
            type="primary"
            @click="createWillModal = true"
            style="margin-bottom: 16px"
          >
            <PlusOutlined /> 创建遗嘱
          </a-button>

          <a-list :data-source="wills">
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a @click="viewWill(item)">查看</a>
                  <a @click="notarizeWill(item)">公证</a>
                </template>
                <a-list-item-meta>
                  <template #title>
                    遗嘱 #{{ item.id }} - {{ item.title }}
                  </template>
                  <template #description>
                    <div>创建时间：{{ item.createdAt }}</div>
                    <div>见证人：{{ item.witnesses.join('、') }}</div>
                    <div>
                      <a-tag v-if="item.notarized" color="gold">
                        <SafetyCertificateOutlined /> 已公证
                      </a-tag>
                      <a-tag v-else color="blue">待公证</a-tag>
                      <a-tag color="green">链上存证</a-tag>
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-tab-pane>

        <!-- 教育基金 -->
        <a-tab-pane key="education" tab="🎓 教育基金">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-statistic
                title="基金总额"
                :value="educationFund.total"
                suffix="万元"
              >
                <template #prefix>💰</template>
              </a-statistic>
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="已发放"
                :value="educationFund.distributed"
                suffix="万元"
              >
                <template #prefix>✓</template>
              </a-statistic>
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="受益人"
                :value="educationFund.beneficiaries"
                suffix="人"
              >
                <template #prefix>👨‍🎓</template>
              </a-statistic>
            </a-col>
          </a-row>

          <a-card title="发放记录" size="small" style="margin-top: 16px">
            <a-table
              :data-source="educationRecords"
              :columns="educationColumns"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'amount'">
                  ¥{{ record.amount.toLocaleString() }}
                </template>
                <template v-if="column.key === 'status'">
                  <a-tag
                    :color="record.status === 'approved' ? 'green' : 'orange'"
                  >
                    {{ record.status === 'approved' ? '已发放' : '待审核' }}
                  </a-tag>
                </template>
              </template>
            </a-table>
          </a-card>

          <a-card title="💡 智能合约规则" size="small" style="margin-top: 16px">
            <a-descriptions :column="1" bordered size="small">
              <a-descriptions-item label="最低GPA要求">3.5</a-descriptions-item>
              <a-descriptions-item label="年度限额">
                10万元/人
              </a-descriptions-item>
              <a-descriptions-item label="自动发放">
                每学期开学前
              </a-descriptions-item>
              <a-descriptions-item label="审核方式">
                DAO投票 + 成绩验证
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-tab-pane>

        <!-- 公益基金 -->
        <a-tab-pane key="charity" tab="❤️ 公益基金">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-statistic
                title="基金总额"
                :value="charityFund.total"
                suffix="万元"
              >
                <template #prefix>❤️</template>
              </a-statistic>
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="已捐赠"
                :value="charityFund.donated"
                suffix="万元"
              >
                <template #prefix>✓</template>
              </a-statistic>
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="受助项目"
                :value="charityFund.projects"
                suffix="个"
              >
                <template #prefix>🎯</template>
              </a-statistic>
            </a-col>
          </a-row>

          <a-card title="公益项目" size="small" style="margin-top: 16px">
            <a-list :data-source="charityProjects">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #title>{{ item.name }}</template>
                    <template #description>
                      <div>捐赠金额：¥{{ item.amount.toLocaleString() }}</div>
                      <div>受益人数：{{ item.beneficiaries }}人</div>
                    </template>
                  </a-list-item-meta>
                  <a-tag color="green">链上存证</a-tag>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </a-tab-pane>

        <!-- 法律存证 -->
        <a-tab-pane key="legal-proof" tab="🔐 法律存证">
          <a-card title="📋 存证记录" size="small">
            <a-list :data-source="legalProofs">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #title>
                      {{ item.title }}
                    </template>
                    <template #description>
                      <div>存证时间：{{ item.timestamp }}</div>
                      <div>哈希：{{ item.hash }}</div>
                      <div>公证机构：{{ item.notary }}</div>
                    </template>
                  </a-list-item-meta>
                  <a-space>
                    <a-tag color="gold">已公证</a-tag>
                    <a-tag color="green">链上存证</a-tag>
                    <a-button
                      size="small"
                      type="link"
                      @click="downloadCertificate(item)"
                    >
                      下载证书
                    </a-button>
                  </a-space>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </a-tab-pane>

        <!-- 合同模板 -->
        <a-tab-pane key="templates" tab="📝 合同模板">
          <a-row :gutter="16">
            <a-col
              v-for="template in documentTemplates"
              :key="template.id"
              :span="8"
            >
              <a-card size="small" hoverable @click="useTemplate(template)">
                <template #title>
                  <FileTextOutlined /> {{ template.name }}
                </template>
                <p>{{ template.description }}</p>
                <a-space>
                  <a-tag>{{ template.category }}</a-tag>
                  <a-tag color="blue">使用{{ template.useCount }}次</a-tag>
                </a-space>
              </a-card>
            </a-col>
          </a-row>
        </a-tab-pane>

        <!-- 智能合约 -->
        <a-tab-pane key="contracts" tab="🔐 智能合约">
          <a-tabs type="card">
            <!-- 合约模板 -->
            <a-tab-pane key="contract-templates" tab="合约模板">
              <a-row :gutter="16">
                <a-col
                  v-for="template in contractTemplates"
                  :key="template.id"
                  :span="12"
                >
                  <a-card size="small" hoverable style="margin-bottom: 16px">
                    <template #title>
                      <SafetyCertificateOutlined /> {{ template.name }}
                    </template>
                    <p>{{ template.description }}</p>
                    <a-descriptions :column="2" size="small">
                      <a-descriptions-item label="类型">
                        <a-tag>{{ template.category }}</a-tag>
                      </a-descriptions-item>
                      <a-descriptions-item label="Gas估算">
                        {{ template.gasEstimate }} ETH
                      </a-descriptions-item>
                      <a-descriptions-item label="参数数量" :span="2">
                        {{ template.parameters.length }} 个
                      </a-descriptions-item>
                    </a-descriptions>
                    <a-button
                      type="primary"
                      block
                      style="margin-top: 12px"
                      @click="selectTemplate(template)"
                    >
                      选择并部署
                    </a-button>
                  </a-card>
                </a-col>
              </a-row>
            </a-tab-pane>

            <!-- 已部署合约 -->
            <a-tab-pane key="deployed-contracts" tab="已部署合约">
              <a-list :data-source="deployedContracts" bordered>
                <template #renderItem="{ item }">
                  <a-list-item>
                    <template #actions>
                      <a @click="viewContract(item)">详情</a>
                      <a
                        v-if="item.status === 'pending'"
                        @click="signContract(item)"
                      >
                        签署
                      </a>
                      <a
                        v-if="item.status === 'active'"
                        @click="executeContract(item)"
                      >
                        执行
                      </a>
                    </template>
                    <a-list-item-meta>
                      <template #title>
                        {{ item.name }}
                        <a-tag
                          :color="
                            item.status === 'active' ? 'success' : 'warning'
                          "
                          style="margin-left: 8px"
                        >
                          {{ item.status === 'active' ? '运行中' : '待激活' }}
                        </a-tag>
                      </template>
                      <template #description>
                        <div>模板：{{ item.template }}</div>
                        <div>地址：{{ item.address }}</div>
                        <div>部署者：{{ item.deployer }}</div>
                        <div>部署时间：{{ item.deployedAt }}</div>
                        <div>签名进度：{{ item.signers.length }} / 3</div>
                      </template>
                    </a-list-item-meta>
                  </a-list-item>
                </template>
              </a-list>
            </a-tab-pane>
          </a-tabs>
        </a-tab-pane>

        <!-- 律师服务 -->
        <a-tab-pane key="lawyer" tab="⚖️ 律师对接">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-card title="🏛️ 合作律所" size="small">
                <a-list :data-source="lawFirms">
                  <template #renderItem="{ item }">
                    <a-list-item>
                      <template #actions>
                        <a @click="consultLawyer(item)">咨询</a>
                        <a @click="viewCases(item)">案例</a>
                      </template>
                      <a-list-item-meta>
                        <template #title>{{ item.name }}</template>
                        <template #description>
                          <div>专长：{{ item.expertise.join('、') }}</div>
                          <div>服务次数：{{ item.serviceCount }}次</div>
                        </template>
                      </a-list-item-meta>
                      <a-rate :value="item.rating" disabled allow-half />
                    </a-list-item>
                  </template>
                </a-list>
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="💼 法律咨询记录" size="small">
                <a-timeline>
                  <a-timeline-item
                    v-for="consult in consultations"
                    :key="consult.id"
                    color="blue"
                  >
                    <p>
                      <strong>{{ consult.topic }}</strong>
                    </p>
                    <p>律师：{{ consult.lawyer }}</p>
                    <p>时间：{{ consult.time }}</p>
                    <a-tag color="green">已解决</a-tag>
                  </a-timeline-item>
                </a-timeline>
              </a-card>
            </a-col>
          </a-row>
        </a-tab-pane>

        <!-- 司法仲裁 -->
        <a-tab-pane key="arbitration" tab="🏛️ 司法仲裁">
          <a-card title="仲裁案件" size="small">
            <a-table
              :data-source="arbitrationCases"
              :columns="arbitrationColumns"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag
                    :color="
                      record.status === 'resolved'
                        ? 'green'
                        : record.status === 'pending'
                          ? 'orange'
                          : 'blue'
                    "
                  >
                    {{
                      record.status === 'resolved'
                        ? '已结案'
                        : record.status === 'pending'
                          ? '审理中'
                          : '待受理'
                    }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'action'">
                  <a-space>
                    <a @click="viewCase(record)">查看</a>
                    <a
                      v-if="record.status === 'resolved'"
                      @click="downloadVerdict(record)"
                      >裁决书</a>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>

          <a-alert
            message="智能合约仲裁"
            description="使用智能合约和DAO投票进行家族内部纠纷仲裁，公平、透明、不可篡改"
            type="info"
            show-icon
            style="margin-top: 16px"
          />
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 创建遗嘱Modal -->
    <a-modal
      v-model:open="createWillModal"
      title="📜 创建遗嘱"
      width="800px"
      @ok="saveWill"
    >
      <a-form layout="vertical">
        <a-form-item label="遗嘱标题">
          <a-input v-model:value="newWill.title" placeholder="如：朱元璋遗嘱" />
        </a-form-item>
        <a-form-item label="遗嘱内容">
          <a-textarea
            v-model:value="newWill.content"
            :rows="8"
            placeholder="详细说明财产分配、家族事务安排等..."
          />
        </a-form-item>
        <a-form-item label="见证人（至少2人）">
          <a-select v-model:value="newWill.witnesses" mode="multiple">
            <a-select-option value="朱棣">朱棣</a-select-option>
            <a-select-option value="朱橚">朱橚</a-select-option>
            <a-select-option value="朱瞻基">朱瞻基</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-checkbox v-model:checked="newWill.requireNotary">
            需要公证处签名确认
          </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 部署智能合约Modal -->
    <a-modal
      v-model:open="contractDeployModal"
      title="部署智能合约"
      width="700px"
      @ok="deployContract"
    >
      <a-form
        v-if="newContract.templateId"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="合约模板">
          <a-input
            :value="
              contractTemplates.find((t) => t.id === newContract.templateId)
                ?.name
            "
            disabled
          />
        </a-form-item>

        <a-form-item label="合约名称">
          <a-input
            v-model:value="newContract.name"
            placeholder="请输入合约名称，如：朱瞻基遗产分配合约"
          />
        </a-form-item>

        <a-divider>合约参数配置</a-divider>

        <a-form-item
          v-for="param in contractTemplates.find(
            (t) => t.id === newContract.templateId,
          )?.parameters || []"
          :key="param.name"
          :label="param.label"
          :required="param.required"
        >
          <a-input
            v-if="param.type === 'text' || param.type === 'address'"
            v-model:value="newContract.parameters[param.name]"
            :placeholder="`请输入${param.label}`"
          />
          <a-input-number
            v-else-if="param.type === 'number'"
            v-model:value="newContract.parameters[param.name]"
            style="width: 100%"
            :min="0"
          />
          <a-date-picker
            v-else-if="param.type === 'datetime'"
            v-model:value="newContract.parameters[param.name]"
            show-time
            style="width: 100%"
          />
          <a-select
            v-else-if="param.type === 'select'"
            v-model:value="newContract.parameters[param.name]"
            style="width: 100%"
          >
            <a-select-option
              v-for="option in param.options"
              :key="option"
              :value="option"
            >
              {{ option }}
            </a-select-option>
          </a-select>
          <a-textarea
            v-else-if="param.type === 'array'"
            v-model:value="newContract.parameters[param.name]"
            :rows="3"
            :placeholder="`请输入${param.label}，多个值用逗号分隔`"
          />
        </a-form-item>

        <a-alert
          message="Gas费用估算"
          :description="`部署此合约预计消耗 ${contractTemplates.find((t) => t.id === newContract.templateId)?.gasEstimate || 0} ETH`"
          type="info"
          show-icon
        />
      </a-form>
    </a-modal>

    <!-- 签署智能合约Modal -->
    <a-modal
      v-model:open="contractSigningModal"
      title="链上签署合约"
      width="800px"
      @ok="confirmSignContract"
    >
      <div v-if="selectedContract">
        <a-descriptions title="合约信息" :column="2" bordered>
          <a-descriptions-item label="合约名称" :span="2">
            {{ selectedContract.name }}
          </a-descriptions-item>
          <a-descriptions-item label="合约模板">
            {{ selectedContract.template }}
          </a-descriptions-item>
          <a-descriptions-item label="合约地址">
            {{ selectedContract.address }}
          </a-descriptions-item>
          <a-descriptions-item label="部署者">
            {{ selectedContract.deployer }}
          </a-descriptions-item>
          <a-descriptions-item label="部署时间">
            {{ selectedContract.deployedAt }}
          </a-descriptions-item>
          <a-descriptions-item label="合约状态">
            <a-tag
              :color="
                selectedContract.status === 'active' ? 'success' : 'warning'
              "
            >
              {{ selectedContract.status === 'active' ? '已激活' : '待激活' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="受益人数量">
            {{ selectedContract.beneficiaries }}
          </a-descriptions-item>
          <a-descriptions-item label="交易哈希" :span="2">
            <a-typography-text :copyable="{ text: selectedContract.txHash }">
              {{ selectedContract.txHash }}
            </a-typography-text>
          </a-descriptions-item>
        </a-descriptions>

        <a-divider>签名记录</a-divider>

        <a-timeline>
          <a-timeline-item
            v-for="(signer, index) in selectedContract.signers"
            :key="index"
            :color="signer.signed ? 'green' : 'gray'"
          >
            <template #dot>
              <SafetyCertificateOutlined
                v-if="signer.signed"
                style="font-size: 16px"
              />
              <ClockCircleOutlined v-else style="font-size: 16px" />
            </template>
            <div>
              <strong>{{ signer.name }}</strong>
              <span
                v-if="signer.signed"
                style="margin-left: 8px; color: #52c41a"
              >
                已签名
              </span>
              <span v-else style="margin-left: 8px; color: #999"> 待签名 </span>
            </div>
            <div v-if="signer.time" style="font-size: 12px; color: #999">
              {{ signer.time }}
            </div>
            <div v-if="signer.signed" style="font-size: 12px; color: #999">
              地址: {{ signer.address }}
            </div>
          </a-timeline-item>
        </a-timeline>

        <a-alert
          v-if="selectedContract.status === 'pending'"
          message="链上签署确认"
          description="您正在进行链上签署操作，签名将被永久记录在区块链上，不可撤销。请确认合约信息无误后再进行签署。"
          type="warning"
          show-icon
          style="margin-top: 16px"
        />

        <a-alert
          v-if="selectedContract.status === 'active'"
          message="合约已激活"
          description="该合约已获得足够签名并已激活，可以执行合约条款。"
          type="success"
          show-icon
          style="margin-top: 16px"
        />
      </div>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.legal-compliance {
  // 样式
}
</style>
